import { reqGetcode, reqRegister, reqLogin, reqUserInfo, reqLogout } from '@/api';
import { getItem, setItem, removeItem } from '@/utils/token';

const state = {
    code: '',
    token: getItem(),
    userInfo: {}
};

const getters = {};

const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    LOGIN(state, token) {
        state.token = token;
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    CLEAR(state) {
        state.token = '';
        state.userInfo = {};
        removeItem()
    }
};

const actions = {
    // 获取验证码
    async getCode({ commit }, phone) {
        let res = await reqGetcode(phone);
        if (res.code == 200) {
            commit('GETCODE', res.data);
            return 'ok';
        }
        return Promise.reject(new Error('faile'));
    },
    // 注册
    async register({ commit }, data) {
        let res = await reqRegister(data);
        if (res.code == 200) {
            return 'ok';
        }
        return Promise.reject(new Error('faile'));
    },
    // 登录
    async login({ commit }, data) {
        let res = await reqLogin(data);
        if (res.code == 200) {
            commit('LOGIN', res.data.token);
            setItem(res.data.token)
            return 'ok';
        }
        return Promise.reject(new Error('faile'));
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
        let res = await reqUserInfo();
        if (res.code == 200) {
            commit('GETUSERINFO', res.data)
            return "ok";
        }
        return Promise.reject(new Error('faile'));
    },
    //退出登录
    async logout({ commit }) {
        let res = await reqLogout()
        if (res.code == 200) {
            commit('CLEAR')
            return "ok"
        } else {
            return Promise.reject(new Error('fail'))
        }
    }
};

export default {
    state,
    getters,
    mutations,
    actions
}